<template>
  <div class="goods-list">
    <h2>商品列表</h2>

    <!-- 商品表格 -->
    <el-table :data="goods" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="goods_name" label="商品名称" width="180"></el-table-column>
      <el-table-column prop="quantity" label="上架数量" width="180"></el-table-column>
      <el-table-column prop="inventory_quantity" label="库存数量" width="180"></el-table-column>
      <el-table-column prop="price" label="单价(元)" width="180"></el-table-column>
      <el-table-column label="操作">
        <template v-slot:default="{ row }">
          <el-button size="mini" type="success" @click="onShelf(row)">上架</el-button>
          <el-button size="mini" type="danger" @click="offShelf(row)">下架</el-button>
          <el-button size="mini" type="warning" @click="editGood(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 上架弹窗 -->
    <el-dialog title="上架商品" v-model="onShelfDialogVisible" width="30%">
      <el-input-number v-model="onShelfQuantity" :min="0" :max="currentGood.inventory_quantity" label="上架数量"></el-input-number>
      <template #footer>
        <el-button @click="onShelfDialogVisible = false">取消</el-button>
        <el-button type="success" @click="confirmOnShelf">确认</el-button>
      </template>
    </el-dialog>

    <!-- 下架弹窗 -->
    <el-dialog title="下架商品" v-model="offShelfDialogVisible" width="30%">
      <el-input-number v-model="offShelfQuantity" :min="0" :max="currentGood.quantity" label="下架数量"></el-input-number>
      <template #footer>
        <el-button @click="offShelfDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmOffShelf">确认</el-button>
      </template>
    </el-dialog>

    <!-- 修改商品弹窗 -->
    <el-dialog title="修改商品" v-model="editDialogVisible" width="30%">
      <el-form :model="editForm">
        <el-form-item label="商品名称">
          <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="单价(元)">
          <el-input-number v-model="editForm.price" :min="0.01" label="单价"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getGoods, updateShelves, changeGoods} from '@/api/goods';

export default {
  setup() {
    const goods = ref([]);
    const onShelfDialogVisible = ref(false);
    const offShelfDialogVisible = ref(false);
    const editDialogVisible = ref(false);
    const onShelfQuantity = ref(1);
    const offShelfQuantity = ref(1);
    const currentGood = ref(null);
    const editForm = ref({
      goods_name: '',
      price: 0,
    });

    const onShelf = (good) => {
      currentGood.value = good;
      onShelfDialogVisible.value = true;
    };

    const confirmOnShelf = async () => {
      if (onShelfQuantity.value <= 0) {
        ElMessage.error('上架数量必须大于0');
        return;
      }

      if (currentGood.value.inventory_quantity < onShelfQuantity.value) {
        ElMessage.error('库存不足，无法上架');
        return;
      }

      try {
        await updateShelves(currentGood.value.id, true, onShelfQuantity.value);
        ElMessage.success(`成功上架 ${onShelfQuantity.value} 件商品`);
        onShelfDialogVisible.value = false;
        onShelfQuantity.value = 1; // 重置输入框
        fetchGoods(); // 刷新商品列表
      } catch (error) {
        ElMessage.error('上架失败，请稍后再试');
      }
    };

    const offShelf = (good) => {
      currentGood.value = good;
      offShelfDialogVisible.value = true;
    };

    const confirmOffShelf = async () => {
      if (offShelfQuantity.value <= 0) {
        ElMessage.error('下架数量必须大于0');
        return;
      }

      if (currentGood.value.quantity + offShelfQuantity.value > currentGood.value.inventory_quantity) {
        ElMessage.error('下架数量超出总库存限制');
        return;
      }

      try {
        await updateShelves(currentGood.value.id, false, offShelfQuantity.value);
        ElMessage.success(`成功下架 ${offShelfQuantity.value} 件商品`);
        offShelfDialogVisible.value = false;
        offShelfQuantity.value = 1; // 重置输入框
        fetchGoods(); // 刷新商品列表
      } catch (error) {
        ElMessage.error('下架失败，请稍后再试');
      }
    };

    const editGood = (good) => {
      editForm.value = { ...good };
      editDialogVisible.value = true;
    };

    const confirmEdit = async () => {
      if (!editForm.value.goods_name || editForm.value.price <= 0) {
        ElMessage.error('名称和价格都是必填字段');
        return;
      }

      try {
        await changeGoods(editForm.value.id, editForm.value.goods_name, editForm.value.price);
        ElMessage.success('商品信息修改成功');
        editDialogVisible.value = false;
        fetchGoods(); // 刷新商品列表
      } catch (error) {
        ElMessage.error('修改失败，请稍后再试');
      }
    };

    const fetchGoods = async () => {
      try {
        goods.value = (await getGoods()).map((good) => ({
          ...good,
          quantity: good.quantity || 0,
          inventory_quantity: good.inventory_quantity || 0,
        }));
      } catch (error) {
        console.error('Failed to fetch goods:', error);
        ElMessage.error('加载商品列表失败，请稍候重试。');
      }
    };

    onMounted(fetchGoods);

    return {
      goods,
      onShelfDialogVisible,
      offShelfDialogVisible,
      editDialogVisible,
      onShelfQuantity,
      offShelfQuantity,
      currentGood,
      editForm,
      onShelf,
      confirmOnShelf,
      offShelf,
      confirmOffShelf,
      editGood,
      confirmEdit,
    };
  },
};
</script>